package com.auto.printer.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.auto.printer.common.exception.MyException;

/**
 * Word 转 Pdf 帮助类
 * 
 * @author admin
 *
 */
public class WordPdfUtil {
    private static boolean license = false;


    
    static {
        try {
            // license.xml放在src/main/resources文件夹下
            InputStream is = WordPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            license = true;
        } catch (Exception e) {
            license = false;
            System.out.println("License验证失败...");
            e.printStackTrace();
        }
    }


    public static File  doc2pdf(String fileUrl, byte[] bytes) throws Exception {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!license) {
           throw new MyException("License验证不通过...");
        }

        try {
            long old = System.currentTimeMillis();
            //新建一个pdf文档
            Path outPutPath = Paths.get(FileUtil.getPrefix(fileUrl) + ".pdf");
            OutputStream os = Files.newOutputStream(outPutPath);
            //Address是将要被转化的word文档
            Document doc = new Document(new ByteArrayInputStream(bytes));
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            os.close();
            //转化用时
            System.out.println("Word 转 Pdf 共耗时：" + ((now - old) / 1000.0) + "秒");
            return outPutPath.toFile();
        } catch (Exception e) {
            System.out.println("Word 转 Pdf 失败...");
           throw e;
        }
    }
}